#pragma once
#include <pthread.h>
#include <ncurses.h>
#include <string>
#include <string.h>
#include <unistd.h>

void GetInput(std::string& input, WINDOW* win, int start_y, int start_x, pthread_mutex_t* lock, int& flag){
  intrflush(win, FALSE);
  keypad(win, TRUE);
  int x = start_x;
  int y = start_y;
  int ch;
  int deviation = 0;
  int max_x, max_y;
  getmaxyx(win, max_y, max_x);
  max_x -= 3;
  max_y -= 2;
  do{
    memset(&ch, 0, sizeof(ch));
    pthread_mutex_lock(lock);
    wmove(win, y, x);
    pthread_mutex_unlock(lock);
    ch = wgetch(win);
    switch(ch){
      case KEY_UP:
        beep();
        break;
      case KEY_DOWN:
        beep();
        break;
      case KEY_RIGHT:
        if(deviation){
          if(x == max_x){
            x = start_x;
            ++y;
          }
          else{
            ++x;
          }
          --deviation;
        }
        else{
          beep();
        }
        break;
      case KEY_LEFT:
        if(x > start_x){
          ++deviation;
          --x;
        }
        else if(y > start_y){
          ++deviation;
          --y;
        }
        else{
          beep();
        }
        break;
      //Enter
      case 13:
        return;
      //Backsapce
      case 0x08:
        if(x > start_x){
          pthread_mutex_lock(lock);
          mvwaddch(win, y, --x, ' ');
          pthread_mutex_unlock(lock);
        }
        else if(y > start_y){
          x = max_x;
          pthread_mutex_lock(lock);
          mvwaddch(win, --y, x, ' ');
          pthread_mutex_unlock(lock);
        }
        else{
          beep();
          break;
        }
        input.pop_back();
        break;
      //Esc
      case 27:
        flag = 1;
        return;
      default:
        if(y == max_y && x == max_x){
          beep();
          break;
        }
        pthread_mutex_lock(lock);
        waddch(win, ch);
        pthread_mutex_unlock(lock);
        if(deviation){
          input.insert(x - start_x, (char*)&ch);
        }
        input += ch;
        if(x == max_x){
          ++y;
          x = start_x;
        }
        else{
          ++x;
        }
        break; 
    } 
  }while(1);
}
